package baseFx.serialization.json.jackson;

import baseFx.serialization.json.BeanSerialize;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.BeanDescription;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializationConfig;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.BeanSerializerModifier;

import java.io.IOException;

public class SerializerModifier extends BeanSerializerModifier {
    @Override
    public JsonSerializer<?> modifySerializer(SerializationConfig config, BeanDescription beanDesc, JsonSerializer<?> serializer) {
        if (serializer.handledType() != null && BeanSerialize.class.isAssignableFrom(serializer.handledType())) {
            return new BeforeSerializer<>(serializer);
        }
        return serializer;
    }

    private static class BeforeSerializer<T> extends JsonSerializer<T> {
        private JsonSerializer<T> serializer;

        public BeforeSerializer(JsonSerializer<T> serializer) {
            this.serializer = serializer;
        }

        @Override
        public void serialize(T t, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
            if (t instanceof BeanSerialize) {
                ((BeanSerialize) t).onBefore();
            }
            this.serializer.serialize(t, jsonGenerator, serializerProvider);
        }
    }
}
